package com.guanzi.nio.c4;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * nio-selector 服务器
 * @author 管子
 * @date 2025/2/22 11:30
 * @description: Server 类
 */
public class Server {

    private static final Logger log = LoggerFactory.getLogger(Server.class);

    /**
     * 任务：完成split方法
     * @param source
     */
    public static void split(ByteBuffer source) {
        // 切换为读模式
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n') {
                // 记录该行的长度
                int length = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    // source的无限模式下，get()方法会移动position
                    target.put(source.get());
                }
                target.flip();
                log.info("读取到消息: {}", Charset.defaultCharset().decode(target));
            }
        }
        // compact()表示将未读的数据移动到buffer的起始位置，切换为写模式
        source.compact();
    }

    public static void main(String[] args) throws IOException {
        // 创建selector，用来管理多个channel
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 非阻塞模式
        ssc.configureBlocking(false);

        // 注册服务端并绑定ACCEPT事件
        SelectionKey sscKey = ssc.register(selector, SelectionKey.OP_ACCEPT, null);
        log.info("注册服务端成功: {}", sscKey);
        ssc.bind(new InetSocketAddress(8080));
        while (true) {
            // 获取注册到selector的监听事件，没有则会阻塞
            log.info("查询事件阻塞");
            selector.select();
            // 因为需要删除selector的事件，所以必须要迭代器
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                // 因为持有selectionKey引用，所以直接删除
                iterator.remove();
                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
                    // 服务端监听并处理客户端连接，没有则会阻塞
                    // accept同时，注册客户端并绑定READ事件到selector里
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    // 对于每一个客户端，都应该有一个专属于自己的buffer接收和读取数据
                    ByteBuffer buffer = ByteBuffer.allocate(4);
                    SelectionKey scKey = sc.register(selector, SelectionKey.OP_READ, buffer);
                    log.info("接收并注册新的客户端连接: {}", scKey);
                } else if (selectionKey.isReadable()) {
                    try {
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        log.info("read: {}", channel);
                        ByteBuffer channelBuffer = (ByteBuffer) selectionKey.attachment();
                        int read = channel.read(channelBuffer);

                        // 如果是客户端断开连接，删除selector的监听事件
                        if (read == -1) {
                            selectionKey.cancel();
                        } else {
                            split(channelBuffer);
                            if (channelBuffer.position() == channelBuffer.limit()) {
                                ByteBuffer newBuffer = ByteBuffer.allocate(channelBuffer.capacity() * 2);
                                channelBuffer.flip();
                                newBuffer.put(channelBuffer);
                                selectionKey.attach(newBuffer);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 客户端断开连接，删除selector的监听事件
                        selectionKey.cancel();
                    }
                }
            }
        }

    }

}
